/*
 * @Description: mark
 * @Author: wangwangwang
 * @Date: 2020-06-28 18:18:01
 * @LastEditors: wangwangwang
 * @LastEditTime: 2021-03-18 11:11:02
 */
import { login } from '@/api/api';
import { getSystemDetails } from '@/api/common';
import { getToken, setToken, removeToken, getUserId, setUserId, setUserInfo, setPerMission, removePerMission } from '@/utils/auth';

const state = {
  token: getToken(),
  id: getUserId(),
  name: '',
  roles: ['admin']
}

const mutations = {
  SET_TOKEN: (state, token) => {
    state.token = token
  },
  SET_USERID: (state, id) => {
    state.id = id
  },
  SET_NAME: (state, name) => {
    state.name = name
  },
  SET_ROLES: (state, roles) => {
    state.roles = roles
  }
}

const actions = {
  login({ commit }, userInfo) {
    const { username, password, } = userInfo;
    return new Promise((resolve, reject) => {
      login({ username: username.trim(), password, type: 1 }).then(response => {
        /**
         * @Description: 存储用户信息
         * @Param: 
         * @Author: wangwangwang
         */
        const { data: { userToken }, data } = response;
        commit('SET_TOKEN', userToken.accessToken);
        commit('SET_USERID', userToken.userId);
        setPerMission(data)
        setToken(userToken.accessToken);
        setUserId(userToken.userId);
        if (userToken.adminStatus == 1) {
          userToken.companyId = null
        }
        userToken.headImg = data.headImg;
        setUserInfo(userToken);
        commit('SET_NAME', userToken.userRealName);
        getSystemDetails({code: 'watermark'}).then(res => {
          if (res.code === 1001) {
            window.sessionStorage.setItem('watermark', res.data.paramValue);
          }
        })
        resolve();
      }).catch(error => {
        reject(error);
      })
    })
  },
  logout({ commit }) {
    return new Promise((resolve) => {
      commit('SET_TOKEN', '')
      commit('SET_ROLES', [])
      commit('SET_USERID', '')
      removeToken()
      removePerMission()
      resolve()
    })
  },

  // remove token
  resetToken({ commit }) {
    return new Promise(resolve => {
      commit('SET_TOKEN', '')
      commit('SET_ROLES', [])
      commit('SET_USERID', '')
      removeToken()
      resolve()
    })
  },
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
